package pl.pawluk.inz.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.web.context.WebApplicationContext;

import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * @author: toshiba
 * Date: 02.03.13
 * Time: 17:39
 * To change this template use File | Settings | File Templates.
 */
public class SpringResourceBundle extends ResourceBundle {
    private static final Log log = LogFactory.getLog(SpringResourceBundle.class);

    private MessageSource messages;

    public SpringResourceBundle() {
        FacesContext fc = FacesContext.getCurrentInstance();
        WebApplicationContext webAppCtx = (WebApplicationContext) fc.getExternalContext().getApplicationMap().get(
                WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        messages = (MessageSource) webAppCtx.getBean("messageSource");
    }

    @Override
    public Locale getLocale() {
        FacesContext fc = FacesContext.getCurrentInstance();
        Locale loc = fc.getApplication().getDefaultLocale();
        if (fc.getExternalContext() != null) {
            loc = fc.getExternalContext().getRequestLocale();
        }
        try {
            UIViewRoot viewRoot = fc.getViewRoot();
            if (viewRoot != null) {
                loc = viewRoot.getLocale();
            }
            if (loc == null) {
                loc = fc.getApplication().getDefaultLocale();
            }

        } catch (Throwable th) {
            log.error(th.getLocalizedMessage(), th);
            loc = Locale.getDefault();
        }
        return loc;
    }

    @Override
    protected Object handleGetObject(String key) {
        try {
            if (log.isDebugEnabled())
                log.debug("handleGetObject: key: " + key);
            Object o = messages.getMessage(key, null, getLocale());
            if (log.isDebugEnabled())
                log.debug("handleGetObject: object: " + o);
            return o;
        } catch (NoSuchMessageException e) {
            log.error(e.getLocalizedMessage(), e);
            return "???" + key + "???";
        }
    }

    @Override
    public Enumeration<String> getKeys() {
        return Collections.enumeration(Collections.EMPTY_LIST);
    }
}